<script setup>
  import { toast } from '@/utils/utils.js'
  import { ref } from 'vue'
  import { login as loginAPI } from '@/apis/user.js'
  // import * as userAPI from '@/apis/user.js'
  import { useUserStore } from '@/stores/user.js'
  import { onLoad } from '@dcloudio/uni-app'

  let query = {}

  onLoad((_query) => {
    query = _query
  })

  const form = ref(null)

  const formData = ref({
    account: '',
    password: '',
  })

  // 和 element-ui 的区别
  // 1. message -> errorMessage
  // 2. 数据解构变化 [] -> { rules: [] }
  const formRules = ref({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: /^[a-zA-Z0-9]{6,8}$/, errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: /^\d{6}$/, errorMessage: '登录密码格式不正确' },
      ],
    },
  })

  const login = async () => {
    await form.value.validate()
    const { data: token } = await loginAPI(formData.value)
    // 走到这里，才确保登录成功
    const { setToken } = useUserStore()
    setToken(token)

    toast('登录成功', 'success')

    if (query.returnURL) {
      // query.returnType 刚好就是跳转方法名称，所以直接用中括号的形式访问函数，然后加小括号调用即可
      // uni[query.returnType]({ url: query.returnURL })
      if (query.returnType === 'switchTab') {
        uni.switchTab({
          url: query.returnURL,
        })
      } else {
        uni.redirectTo({
          url: query.returnURL,
        })
      }
    } else {
      uni.switchTab({
        url: '/pages/my/index',
      })
    }
  }
</script>

<template>
  <uni-forms class="login-form" ref="form" :model="formData" :rules="formRules">
    <!-- // 和 element-ui 的区别 -->
    <!-- 1. prop -> name -->
    <uni-forms-item name="account">
      <input
        v-model="formData.account"
        type="text"
        placeholder="请输入账号"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        v-model="formData.password"
        type="text"
        placeholder="请输入密码"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="login">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
